<template>
  <div class="fillcontain">
    <!-- 增加 -->
    <bt-col-header title="新增模型管理"></bt-col-header>
    <div class="page-content">
      <div class="head-title"><i class="el-icon-vwedit">    {{entitlyTitle}}</i></div>
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="80px"
        class="form-container"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="模型标识" prop="entityIdentify">
              <el-input
                v-model="dataForm.entityIdentify"
                :disabled="isEdit"
                @blur="setPkgName"
                placeholder="模型标识"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型名称" prop="entityName">
              <el-input
                :disabled="isView"
                v-model="dataForm.entityName"
                placeholder="模型名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="包路径" prop="pkgName">
              <el-input
                v-model="dataForm.pkgName"
                disabled
                placeholder="包路径"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有效" prop="isEffect">
              <el-switch
                :disabled="isView"
                v-model="dataForm.isEffect"
                active-color="#13ce66"
                inactive-color="#ff4949"
                on-value="1" on-text="是" off-text="否" off-value="0"
              >
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :disabled="isView"
            :rows="2"
            v-model="dataForm.remark"
            placeholder="备注"
          ></el-input>
        </el-form-item>
      </el-form>

      <div class="mb10 pl20">
        <!-- <div class="content-title"><span>因子</span></div> -->
        <div class="padding_10_0">
              <bt-col-header title="因子"></bt-col-header>
        </div>
        <div class="page-content">
  <!-- <el-row class="mb10">
            <el-col :span="4">
              <el-button
                :disabled="isView"
                type="danger"
                size="mini"
                style="margin-left: 10px"
                plain
                @click="addItem()"
                >新增</el-button
              >
            </el-col>
          </el-row> -->

          <el-form ref="dataItemForm" :model="itemDataForm">
            <el-table
              :data="itemDataForm.itemData"
              height="250"
              border
              style="width: 100%"
            >
              <el-table-column
                header-align="center"
                align="center"
                prop="itemName"
                label="因子名称"
              >
                <template slot-scope="scope">
                  <el-form-item
                    v-if="scope.row.itemType == 'List'"
                    :rules="itemRule.itemName"
                    :prop="'itemData.' + scope.$index + '.itemName'"
                  >
                    <el-input
                      v-model="scope.row.itemName"
                      :disabled="isView"
                      placeholder="因子名称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item
                    v-else
                    style="margin: 0 !important"
                    :prop="'itemData.' + scope.$index + '.itemName'"
                  >
                    <el-select
                      :disabled="isView"
                      v-model="scope.row.itemName"
                      filterable
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in itemNames"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label"
                        @click.native="changeEntityitemName(item, scope)"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="itemIdentify"
                label="因子标识"
              >
                <template slot-scope="scope">
                  <el-form-item
                    :rules="itemRule.itemIdentify"
                    :prop="'itemData.' + scope.$index + '.itemIdentify'"
                  >
                    <el-input
                      :disabled="isView"
                      v-model="scope.row.itemIdentify"
                      placeholder="因子标识"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="itemDesc"
                label="因子类型"
              >
                <template slot-scope="scope">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item
                        :rules="itemRule.itemType"
                        :prop="'itemData.' + scope.$index + '.itemType'"
                        class="tb-colum"
                      >
                        <el-select
                          :disabled="isView"
                          v-model="scope.row.itemType"
                          filterable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="item in itemTypes"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            @click.native="changeEntityItemType(item, scope)"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        v-if="scope.row.itemType == 'List'"
                        class="tb-colum"
                      >
                        <el-select
                          :disabled="isView"
                          v-model="scope.row.itemCls"
                          filterable
                          placeholder="请选择"
                        >
                          <el-option
                            v-for="item in entitys"
                            :key="item.pkgName"
                            :label="item.label"
                            :value="item.pkgName"
                            @click.native="changeEntityItem(item, scope.row)"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                prop="itemIdentify"
                label="初始化方法"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click.native.prevent="
                      configureclick(scope.$index, itemDataForm.itemData)
                    "
                    >查看
                  </el-button>
                </template>
              </el-table-column>
              <!-- <el-table-column header-align="center" align="center" label="操作">
                <template slot-scope="scope">
                  <el-button
                    :disabled="isView"
                    type="text"
                    size="small"
                    @click.native.prevent="deleteItem(scope.$index, itemDataForm.itemData)
                    "
                    >删除
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </el-form>
        </div>
        
      </div>

      <div class="content-footer">
        <!-- <el-button type="danger" :disabled="isView" @click="dataFormSubmit()"
          >确定</el-button
        > -->
        <el-button @click="toList">返回</el-button>
      </div>
    </div>
    
    <!-- 弹窗, 新增 / 修改 -->
    <configure
      v-if="configureVisible"
      :editData="editData"
      :pzIndex="pzIndex"
      @actionList="getactionList"
      :itemNames="paramslist"
      ref="configure"
    ></configure>
  </div>
  <!--  </el-dialog>-->
</template>

<script>
import {
  entityList,
  saveOrUpdate,
  getInfo,
  delItem,
  getitemNames,
} from "@/api/baseConfig/entity";
import bus from "../../../../../busEvent";
import configure from "./configure";
import constant from "../../../../../api/constant";
import axios from "axios";
import Vue from "vue";

export default {
  data() {
    var validateIdentify = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("标识不能为空"));
      } else {
        var patrn = /^[a-z][a-zA-Z0-9]{0,50}$/;
        // console.log(value);
        if (!patrn.test(value)) {
          callback(new Error("标识由字母和数字组成，且首字母为小写长度小于50"));
        } else {
          callback();
        }
      }
    };
    var validateName = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("名称不能为空"));
      } else {
        var regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/im;
        var regCn = /[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im;

        if (regEn.test(value) || regCn.test(value) || value.length >= 50) {
          callback(new Error("名称不能包含特殊字符，且长度小于50"));
        } else {
          callback();
        }
      }
    };
    return {
      entitlyTitle: '',
      iseditadd: false,
      isView: false,
      actionList: [],
      editData: [],
      paramslist: [],
      addoRedit: "",
      pzIndex: 0,
      actionUrl: constant.DR + "/rule/entity/doImport",
      itemTypes: constant.ruleConfig.entityItemType,
      dataList: [],
      fileList: [],
      visible: false,
      isEdit: false,
      configureVisible: false,
      dataForm: {
        id: null,
        entityId: null,
        entityName: "",
        entityDesc: "",
        entityIdentify: "",
        pkgName: "",
        remark: "",
        isEffect: "1",
      },
      entitys: [],
      itemNames: [],
      dataRule: {
        entityName: [{ validator: validateName, trigger: "blur" }],
        entityIdentify: [{ validator: validateIdentify, trigger: "blur" }],
      },
      itemDataForm: {
        itemData: [
          {
            actionInfo: {},
            creTime: null,
            creUserId: null,
            entityId: null,
            entityIdentify: "",
            enumList: null,
            enumName: null,
            isEffect: "",
            itemCls: "",
            itemDesc: "",
            itemId: null,
            itemIdentify: "",
            itemName: "",
            itemObjType: "",
            itemType: "String",
            itemValue: null,
            qualityId: null,
            remark: null,
          },
        ],
      },
      itemRule: {
        itemName: [{ validator: validateName, trigger: "blur" }],
        itemIdentify: [{ validator: validateIdentify, trigger: "blur" }],
        itemType: [
          { required: true, message: "属性类型不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    let id = this.$route.params.id;
    // console.log(this.$route.query.isView);
    if (this.$route.query.isView) {
      this.entitlyTitle = '查看模型'
      this.isView = this.$route.query.isView;
    } else if (this.$route.query.isEdit){
      this.entitlyTitle = '编辑模型'
    } else {
      this.entitlyTitle = '新增模型'
    }
    this.init(id);
    this.getEntityCls();
    this.getitemNameData(id);
  },
  components: {
    configure,
  },
  methods: {
    // 获取因子名称
    getitemNameData(id) {
      this.$store.dispatch("loading/CHANGE_LOADING", true);
      getitemNames({})
        .then((res) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
          // console.log(res);
          if (res.data.data) {
            let list = res.data.data;
            list.forEach((ele, index) => {
              ele.label = ele.qualityName;
              ele.value = ele.qualityId;
            });
            this.itemNames = list;
            // console.log(this.itemNames);
          }
        })
        .catch((err) => {
          this.$store.dispatch("loading/CHANGE_LOADING", false);
        });
    },
    getactionList(value) {
      // console.log(value, "value");
      value.actionList.itemId = this.itemDataForm.itemData[
        value.pzIndex
      ].itemId;
      this.itemDataForm.itemData[value.pzIndex].actionInfo = value.actionList;
    },
    // 上传excel
    submitUpload(file) {
      // console.log("上传" + file.name);
      if (file.name == "") {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }
      let fileFormData = new FormData();
      fileFormData.append("uploadFile", file, file.name);
      const instance = axios.create({
        withCredentials: true, // 一定要加这个，不用设置什么请求头
        headers: {
          "Content-Type": "multipart/form-data",
          token: Vue.cookie.get("token"),
        },
      });
      instance
        .post(constant.DR + "/rule/entity/doImport", fileFormData)
        .then((res) => {
          // console.log(res);
          if (res.data && res.data.resultCode == constant.SUCCESS) {
            this.$message.success(res.data.resultMsg);
            res.data.data.forEach((item) => {
              this.itemDataForm.itemData.push(item);
            });
          } else {
            this.$message.error(res.data.resultMsg);
          }
        });
    },
    beforeAvatarUpload(file) {
      const isExcel =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isExcel) {
        this.$message.error("上传文件只能是 xls或xlsx 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 2MB!");
        return false;
      }

      this.submitUpload(file);

      return true;
    },
    downTemlate(url) {
      if (url) {
        const downloadElement = document.createElement("a");
        const href = url; // 创建下载的链接
        downloadElement.href = href;
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
      }
    },
    toList() {
      constant.clearTag(this);
      this.$router.push({ name: constant.routerName.listEntity });
    },
    init(id) {
      this.visible = true;
      this.dataList = [];

      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (id && id != "undefined") {
          this.dataForm.id = id;
          this.isEdit = true;
          let params = {
            id: this.dataForm.id + "",
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          getInfo(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data.data && res.data.resultCode === 0) {
                this.dataForm = res.data.data.entity;
                this.itemDataForm.itemData = res.data.data.entityItems;
                // console.log(this.itemDataForm.itemData, "22");
                if (this.itemDataForm.itemData.length) {
                  this.paramslist = [];
                  this.itemDataForm.itemData.forEach((item, index) => {
                    this.paramslist[index] = {
                      label: item.itemName,
                      value: item.itemName,
                    };
                  });
                }
              }
            })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
        }
      });
    },

    setPkgName() {
      let pkg =
        this.dataForm.entityIdentify.substring(0, 1).toLocaleUpperCase() +
        this.dataForm.entityIdentify.substring(
          1,
          this.dataForm.entityIdentify.length
        );
      this.dataForm.pkgName = "com.drools.common.entity.clm." + pkg;
    },

    // 获取实体类列表
    getEntityCls() {
      entityList({}).then((res) => {
        this.entitys = [];
        if (res.data.data) {
          res.data.data.forEach((item, index) => {
            item["label"] = item.entityIdentify + "-" + item.entityName;
            this.entitys.push(item);
          });
          // console.log(this.paramslist, "this.paramslist");
          let str = {
            pkgName: "java.lang.String",
            label: "String",
          };
          this.entitys.push(str);
        }
      });
    },
    //
    // 新增属性
    addItem() {
      let item = {
        itemName: "",
        itemIdentify: "",
        itemDesc: "",
        itemCls: "",
        itemType: "",
        entityIdentify: "",
      };
      this.itemDataForm.itemData.push(item);
    },

    deleteItem(index, rows) {
      this.$confirm(`确定要删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let row = rows[index];
          if (row.itemId) {
            delItem(JSON.stringify(row)).then((res) => {
              rows.splice(index, 1);
            });
          } else {
            rows.splice(index, 1);
          }
        })
        .catch(() => {});
    },
    //配置
    configureclick(index, rows) {
      // console.log(rows,index);
      this.configureVisible = true;
      this.editData = rows;
      this.pzIndex = index;
      this.$nextTick(() => {
        this.$refs.configure.init(index);
        // 编辑、查看
         this.$refs.configure._data.dataForm.entityId = this.$route.params.id
        if (rows[index].actionInfo) {
          this.$refs.configure._data.dataForm.entityId = rows[index].entityId
          // console.log(this.$refs.configure._data.dataForm);
          this.$refs.configure._data.dataForm.params = []
          this.$refs.configure._data.dataForm.methodName = rows[index].actionInfo.methodName;
          this.$refs.configure._data.dataForm.qualityType = rows[index].actionInfo.actionName;
          this.$refs.configure._data.dataForm.actionMethodType = rows[index].actionInfo.actionMethodType
            // console.log(typeof rows[index].actionInfo.methodParams,'methodParams');
          if (rows[index].actionInfo.methodParams) {
            if (typeof rows[index].actionInfo.methodParams == 'string') {   
              this.$refs.configure._data.dataForm.params = JSON.parse(rows[index].actionInfo.methodParams);
            } else {
              this.$refs.configure._data.dataForm.params = rows[index].actionInfo.methodParams
            }
          }
          this.$refs.configure._data.dataForm.actionId =
            rows[index].actionInfo.actionId;
        }
      });
    },
    changeEntityItemType(item, row) {
      // console.log(item, row);
      if (item.value === "List") {
        row.row.qualityId = null;
        // console.log(row);
        this.itemDataForm.itemData[row.$index].itemObjType = "3";
      } else {
        this.itemDataForm.itemData[row.$index].itemObjType = "1";
      }
    },
    // 因子名称下拉框
    changeEntityitemName(item, row) {
      // console.log(item, row);
      this.itemDataForm.itemData[row.$index].qualityId = item.value;
      this.itemDataForm.itemData[row.$index].itemIdentify =
        item.qualityIdentify;
      // if (item.) {

      // }
      // console.log(this.itemDataForm.itemData[row.$index]);
    },
    changeEntityItem(item, row) {
      let list = this.itemDataForm.itemData.filter(
        (i) => i.itemCls === item.pkgName
      );
      if (list && list.length > 1) {
        row.itemCls = "";
        this.$message.error("属性标识不能重复");
      }
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$refs["dataItemForm"].validate((valid1) => {
            if (valid1) {
              // console.log(this.itemDataForm.itemData);
              let params = {
                entity: JSON.stringify(this.dataForm),
                entityItems: JSON.stringify(this.itemDataForm.itemData),
                // actionList: JSON.stringify(this.actionList),
              };
              this.$store.dispatch("loading/CHANGE_LOADING", true);
              saveOrUpdate(params)
                .then((res) => {
                  this.$store.dispatch("loading/CHANGE_LOADING", false);
                  if (res.data && res.data.resultCode === 0) {
                    this.$message({
                      message: "操作成功",
                      type: "success",
                      duration: 1500,
                      onClose: () => {
                        this.visible = false;
                        this.dataForm = {
                          entityId: null,
                          entityName: "",
                          entityDesc: "",
                          entityIdentify: "",
                          pkgName: "",
                          remark: "",
                          isEffect: "1",
                        };
                        this.itemDataForm.itemData = [];
                        this.entitysProperties = [];
                        // this.$emit('refreshDataList')
                        this.toList();
                      },
                    });
                  } else {
                    this.$message.error(res.data.resultMsg);
                  }
                })
                .catch((err) => {
                  this.$store.dispatch("loading/CHANGE_LOADING", false);
                });
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  padding: 10px;
  background-color: rgba(248, 248, 248, 1);
  margin-bottom: 10px;
}

.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}

.el-table__row .el-form-item {
  margin-bottom: 18px !important;
  margin-top: 18px !important;
}
.dialog-footer {
  display: block;
  padding: 10px;
  text-align: center;
}
</style>
